import json

# 数据存储文件
DATA_FILE = "scores.json"

# 载入数据
def load_data():
    try:
        with open(DATA_FILE, "r", encoding="utf-8") as f:
            return json.load(f)
    except FileNotFoundError:
        return []

# 保存数据
def save_data(data):
    with open(DATA_FILE, "w", encoding="utf-8") as f:
        json.dump(data, f, ensure_ascii=False, indent=4)

# 记录成绩
def record_score():
    name = input("请输入学生姓名：")
    student_id = input("请输入学生学号：")
    course = input("请输入课程名称：")
    score = input("请输入成绩 (0-100)：")
    if not (0 <= int(score) <= 100):
        print("成绩范围错误，请重新输入！")
        return

    data = load_data()
    data.append({
        "姓名": name,
        "学号": student_id,
        "课程": course,
        "成绩": int(score)
    })
    save_data(data)
    print("成绩已成功记录!")

# 查询成绩
def query_score():
    print("请选择查询方式：")
    print("1. 按学生姓名查询")
    print("2. 按学生学号查询")
    print("3. 按课程名称查询")
    choice = input("请输入选项序号：")
    data = load_data()

    if choice == "1":
        name = input("请输入学生姓名：")
        for record in data:
            if record["姓名"] == name:
                print(record)
    elif choice == "2":
        student_id = input("请输入学生学号：")
        for record in data:
            if record["学号"] == student_id:
                print(record)
    elif choice == "3":
        course = input("请输入课程名称：")
        for record in data:
            if record["课程"] == course:
                print(record)
    else:
        print("无效选项！")

# 统计课程成绩
def statistic_course():
    course = input("请输入课程名称：")
    data = load_data()

    scores = [record["成绩"] for record in data if record["课程"] == course]
    if not scores:
        print("未找到该课程的成绩信息！")
        return

    avg = sum(scores) / len(scores)
    max_score = max(scores)
    min_score = min(scores)
    print(f"课程 {course} 的平均分为：{avg:.2f}")
    print(f"最高分为：{max_score}")
    print(f"最低分为：{min_score}")

# 主菜单
def main_menu():
    while True:
        print("=" * 30)
        print("欢迎使用学生成绩管理系统")
        print("=" * 30)
        print("请选择操作：")
        print("1. 记录学生成绩")
        print("2. 查询学生成绩")
        print("3. 统计课程成绩")
        print("4. 退出系统")
        choice = input("请输入选项序号：")

        if choice == "1":
            record_score()
        elif choice == "2":
            query_score()
        elif choice == "3":
            statistic_course()
        elif choice == "4":
            print("感谢使用学生成绩管理系统，再见！")
            break
        else:
            print("无效选项，请重新输入！")

# 程序入口
if __name__ == "__main__":
    main_menu()
